﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace PIM_ATE.Electrical
{
    class ClsDataAllStatus
    {
        public int Id { get; set; }
        public string ProductSN { get; set; }
        public string Status { get; set; }
        public DateTime Time { get; set; }
        public string Remark1 { get; set; }
        public string Remark2 { get; set; }
        public string Remark3 { get; set; }
    }
    class ClsDataAllStatusBuilder
    {
        const string TABLE_NAME = "tb_AllStatus";
        string m_sConnect;
        ClsDataAllStatus m_allStatus;
        bool m_isEnable;

        public ClsDataAllStatusBuilder(string alias)
        {
            m_sConnect = alias;
            IniFile.SetFileName(System.Windows.Forms.Application.StartupPath + "\\JcDevices.ini");
            m_isEnable = IniFile.IniReadValue("Settings", "IsUploadData", "1") != "0";
        }

        public void construct(ClsDataAllStatus Status)
        {
            m_allStatus = Status;
        }

        public bool updateStatus(out int id, out DateTime time)
        {
            id = 0; time = DateTime.Now;
            if (!m_isEnable || GDefine.IS_LOCAL_RESULT_ANTENNA) return true;

            try
            {
                string sRecordTime = "";
                if (!GDefine.IS_LOCAL_RESULT_ANTENNA)
                {
                    sRecordTime = PIMFunction.getTime(m_sConnect);
                    if (sRecordTime == null || sRecordTime == "")
                    {
                        System.Windows.Forms.MessageBox.Show("无法获取服务器时间");
                        return false;
                    }
                }
                else
                {
                    sRecordTime = DateTime.Now.ToString();
                }
                DateTime dtRecordTime = DateTime.Parse(sRecordTime);
                time = m_allStatus.Time = dtRecordTime;

                using (var tran = MicroDBHelper.UseTransaction(IsolationLevel.RepeatableRead, m_sConnect))
                {
                    string sValue = "'" + m_allStatus.ProductSN + "','" + m_allStatus.Status + "','" + m_allStatus.Time.ToString("yyyy-MM-dd HH:mm:ss.fff") + "'";
                    string sSql = String.Format("insert into {0} ([ProductSN],[Status],[Time]) values ({1}) select @@identity as ID;", TABLE_NAME, sValue);
                    string sID = MicroDBHelper.ExecuteDataTable(sSql, null, m_sConnect).Rows[0]["ID"].ToString();
                    id = int.Parse(sID);
                    tran.MarkSuccess();
                }
            }
            catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); return false; }
            return true;
        }
    }
}
